﻿using CoachingOrganizer.ClientInfrastructure.Services;
using CoachingOrganizer.ClientInfrastructure.ServicesEntities.LocalStorage;
using CoachingOrganizer.Database.DataAccessLayer;
using CoachingOrganizer.Toolkit.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CoachingOrganizer.ClientAdapters.LocalStorage
{
    public abstract class LocalStorageAdapterBase : ILocalStorageService
    {
        private readonly MainDAL _mainDAL;

        public LocalStorageAdapterBase()
        {
            _mainDAL = CreateMainDal();
        }

        public ActionResult<IEnumerable<IPeriodInfo>> EnumeratePeriods()
        {
            ActionResult result = _mainDAL.DbManager.SafeRun(() => _mainDAL.LoadPeriods());
            return result.IsValid ? ActionResult<IEnumerable<IPeriodInfo>>.GetValidResult(_mainDAL.Periods) : ActionResult<IEnumerable<IPeriodInfo>>.GetErrorResult(result);
        }

        public ActionResult<IPeriodInfo> CreateNewPeriod()
        {
            return _mainDAL.DbManager.SafeRequest<IPeriodInfo>(() =>
            {
                PeriodDAL newPeriod = _mainDAL.CreateNewPeriod();
                _mainDAL.AddPeriod(newPeriod);
                return newPeriod;
            });
        }

        protected abstract MainDAL CreateMainDal();
    }
}
